﻿namespace Chunker.Inpe {
    using System;
    using System.IO;
    using System.Linq;
    using Chunker.Inpe.Data.SqlServer;

    public class InpeAnalyser {

        public static void CountChunkColition(int idConfiguration) {
            using (var entities = new InpeEntitiesSqlServer()) {
                Console.WriteLine("Getting data...");
                entities.CommandTimeout = 10000;
                var groups = entities.ImageChunk
                                .OrderBy(x => x.Image.Date.Day)
                                .Where(x => x.Image.Configuration.IdConfiguration == idConfiguration)
                                .GroupBy(x => x.ContentHash)
                                .Where(x => x.Count() > 1)
                                .OrderByDescending(x => x.Count())
                                .ToList();

                Console.WriteLine("Writing file...");
                using (StreamWriter writer = new StreamWriter("output.txt")) {
                    long totalEconomy = 0;
                    for (int i = 0; i < groups.Count; i++) {
                        var group = groups.ElementAt(i);
                        long length = (group.First().End - group.First().Start);
                        int count = group.Count();
                        long economy = (length * count) - length;
                        totalEconomy += economy;

                        writer.WriteLine("Chunk [" + (i + 1) + "] " + group.Key + " - Count: " + count);
                        writer.WriteLine("Length: " + length);
                        writer.WriteLine("Economy: (" + length + " * " + count + ") - " + length + " = " + economy + " bytes");
                        //writer.WriteLine("Images: ");
                        //for (int j = 0; j < group.Count(); j++) {
                        //    ImageChunk chunk = group.ElementAt(j);
                        //    if (!chunk.ImageReference.IsLoaded) {
                        //        chunk.ImageReference.Load();
                        //    }

                        //    writer.WriteLine("\t" + chunk.Image.FileName + " - Start: " + chunk.Start + " - End: " + chunk.End);
                        //}

                        writer.WriteLine();
                    }

                    writer.WriteLine("Total economy: " + totalEconomy + " bytes");
                }
            }
        }
    }
}
